package com.hava.demo.controller;

import com.hava.demo.entity.IdOneEntity;
import com.hava.demo.service.jpa.IdOneJPAService;
import com.hava.web.MediaType;
import com.hava.web.rest.Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.List;

/**
 * Created by zhanpeng on 15-11-27.
 */
@RestController
@RequestMapping(value = "/demo/rest/v1/IdOneJPA")
public class IdOneJPARestController {

    @Autowired
    private IdOneJPAService service;

    //GET /entity : get entity all list
    //注意：这里与springside不同的地方是选择使用google common MediaType
    @RequestMapping(method = RequestMethod.GET, produces = MediaType.JSON)
    public List<IdOneEntity> list() {
        return service.getAll();
    }

    //GET /entity/{id} : get entity.id={id} object
    @RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = MediaType.JSON)
    public IdOneEntity get(@PathVariable("id") Long id) {

        IdOneEntity entity = service.get(id);

        if (entity == null) {
            String message = "OnlyOne Object :id {" + id + "} not existed.";
            System.out.println(message);
        }

        return entity;
    }

    //POST /entity : create new entity object
    @RequestMapping(method = RequestMethod.POST, consumes = MediaType.JSON)
    public ResponseEntity<?> create(@RequestBody IdOneEntity entity, UriComponentsBuilder uriBuilder) {

        System.out.println("create");
        //System.out.println("input:" + test);
        //TODO:JSR303校验

        service.create(entity);

        //按照Restful风格，返回新对象的
        HttpHeaders httpheader = new HttpHeaders();
        String entity_url = null;

        //通过反射获取entity的url
        String EntityURL = Entity.URL(this) + "/" + entity.getId();

        System.out.println("EntityURL" + EntityURL);

        //生成Respone header显示Entity创建后的资源路径
        URI uri = uriBuilder.path(EntityURL).build().toUri();
        httpheader.setLocation(uri);
        ResponseEntity responseEntity = new ResponseEntity(httpheader, HttpStatus.CREATED);

        return responseEntity;
    }

    //PUT /entity/{id} : update entity.id={id}
    @RequestMapping(method = RequestMethod.PUT, value = "/{id}", consumes = MediaType.JSON)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void update(@RequestBody IdOneEntity entity, @PathVariable("id") Long id) {
        entity.setId(id);
        service.update(entity);
    }

    //DELETE /entity/{id} : delete entity.id={id}
    @RequestMapping(method = RequestMethod.DELETE, value = "/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void delete(@PathVariable("id") Long id) {
        service.delete(id);
    }
}